package com.example.test.chapter7.ratingbar;

import java.util.ArrayList;

import com.example.test.R;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

public class RateListActivity extends ListActivity {

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		ArrayList<RowModel> list = new ArrayList<RowModel>();

		for (String s : SmartPhones) {
			list.add(new RowModel(s));
		}

		setListAdapter(new RatingAdapter(list));
	}

	private RowModel getModel(int position) {
		return (((RatingAdapter) getListAdapter()).getItem(position));
	}

	class RatingAdapter extends ArrayAdapter<RowModel> {
		RatingAdapter(ArrayList<RowModel> list) {
			super(RateListActivity.this, R.layout.row, list);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			ViewWrapper wrapper;
			RatingBar rate;
			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.ratingbar, parent, false);
				wrapper = new ViewWrapper(row);
				row.setTag(wrapper);
				rate = wrapper.getRate();
				RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
					public void onRatingChanged(RatingBar ratingBar,
							float rating, boolean fromTouch) {
						Integer myPosition = (Integer) ratingBar.getTag();
						RowModel model = getModel(myPosition);
						model.rating = rating;
						LinearLayout parent = (LinearLayout) ratingBar
								.getParent();
						TextView label = (TextView) parent
								.findViewById(R.id.label_rating);
						label.setText(model.toString());
					}
				};
				rate.setOnRatingBarChangeListener(l);
			} else {
				wrapper = (ViewWrapper) row.getTag();
				rate = wrapper.getRate();
			}

			RowModel model = getModel(position);

			wrapper.getLabel().setText(model.toString());
			rate.setTag(new Integer(position));
			rate.setRating(model.rating);
			return (row);
		}
	}

	class RowModel {
		String label;
		float rating = 0.0f;

		RowModel(String label) {
			this.label = label;
		}

		public String toString() {
			if (rating >= 3.0) {
				return (label.toUpperCase());
			}
			return (label);
		}
	}

	static final String[] SmartPhones = new String[] { "HTC Rezound",
			"Samsung Galaxy S II Skyrocket", "Samsung Galaxy Nexus",
			"Motorola Droid Razr", "Samsung Galaxy S", "Samsung Epic Touch 4G",
			"iPhone 4S", "HTC Titan" };
}
